/*
 * Copyright (C) 2011, EADS France
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 */

package xowl.interpreter.impl;

import xowl.utils.Values;
import xowl.interpreter.XOWLException;

/**
 *
 * @author Laurent WOUTERS
 */
public class StatementForRunner extends StatementRunner {
    private xowl.lang.actions.For statement;
    private boolean isInitDone;
    private boolean isAtLoopEnd;

    public StatementForRunner(xowl.lang.actions.For statement, ThreadRunner runner) {
        super(runner);
        this.statement = statement;
        this.isInitDone = false;
        this.isAtLoopEnd = false;
    }

    @Override public String getFile() { return statement.getFile(); }
    @Override public int getLine() { return statement.getLine(); }
    @Override public void execute() throws XOWLException {
        if (!isInitDone) {
            // First execution: Push FOR context with variable
            ThreadContext context = runner.contextCreate();
            context.assign(statement.getVariable(), runner.evaluator.evaluate(runner.evaluator, statement.getExpressionAs(null)));
            isInitDone = true;
        }
        
        if (isAtLoopEnd) {
            // Pop iteration specific context
            // Execute loop step
            runner.contextPop();
            runner.statementPush(statement.getStep());
            isAtLoopEnd = false;
        } else {
            // check condition
            boolean condition = Values.isTrue(runner.evaluator.evaluate(runner.evaluator, statement.getCondition()));
            if (condition) {
                // execute iteration
                runner.contextCreate();
                runner.statementPush(statement.getContains());
                isAtLoopEnd = true;
            } else {
                // Exit loop: Pop FOR context, pop itself
                runner.contextPop();
                runner.statementPop();
            }
        }
    }
    @Override public boolean onBreak() {
        // Was in an iteration => pop iteration specific context and FOR context
        runner.contextPop();
        runner.contextPop();
        return false;
    }
}
